package com.shop.dao;

import java.util.List;






import org.hibernate.Session;

import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.shop.util.HibernateUtil;

import com.shop.entity.User;

public class UserDaoImpl {

  
    
  
    //	加入用户到数据库中
    public User addUser(User user) {
    	Session session = null; 
    	session = HibernateUtil.openSession();
    	Transaction tx =session.beginTransaction();
    	session.save(user);
        tx.commit();
        session.close();
        return user;
    } 
    
    	public User findUserByUserName(String username){
    		User u=new User( );
        Session session = HibernateUtil.openSession();
        Query query=session. createQuery(" from User where username=" +"'"+username+"'");
        u = (User) query . uniqueResult( );
        if(u!=null){
        	 return u;
        }else{
        	return null;
        }
       
    }
    //	判断用户是否存在
    public boolean isExist(User user){
    	Session session = null;
    	session = HibernateUtil.openSession();
    	String hql = "from User where username =  ? and password = ?";
		Query query = session.createQuery(hql).setProperties(user);
		query.setParameter(0,user.getUsername());
		query.setParameter(1,user.getPassword());
		List<User> list=query.list();
		
		if(list.size()>0){
			user=list.get(0);
			return true;
		}else{
			
			return false;
		}
			
	
    }
    //	查询数据库中的用户
    public List<User> getAllUser() {
    	Session session = null;
    	session = HibernateUtil.openSession();
    	String hql = "from User";
    	Query query= session.createQuery(hql);
		List<User> ulist=query.list();
        return query.list();
    }

    public User findUserById(int id) {
		Session session = null;
		session = HibernateUtil.openSession();
		String hql = "from User where id=?";
		Query query = session.createQuery(hql);
		query.setParameter(0, id);
		return (User) query.uniqueResult();
	}


	public boolean updateUser(User user) {
		Session session = null;
			try {
			session = HibernateUtil.openSession();
			Transaction tran = session.beginTransaction();
			Query query = session.createQuery("update User set username=?,password=? where id=?");
			query.setParameter(0, user.getUsername());
			query.setParameter(1, user.getPassword());
			query.setParameter(2, user.getId());
			return query.executeUpdate() > 0;

		} catch (Exception e) {
			e.printStackTrace();
//				tran.rollback();
		} finally {
			if (null != session) {
				session.close();
			}
		}
		return false;
	}

}
